package com.fingard.dsp.bank.directbank.spdb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.ftp.BizFtpClient;
import com.fingard.net.ftp.BizFtpResp;
import com.fingard.text.StringHelper;
import com.tongtech.wtp.WtpDownloadFile;
import com.tongtech.wtp.WtpUploadFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class SPDB11Base extends DirectBase {
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * WTP文件上传
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    protected String[] upFileToBank(String filePath) {
        String[] tmpStrRet = new String[]{"", ""};
        try {
            WtpUploadFile upload = new WtpUploadFile();
            upload.setLocalFileName(filePath);
            WriteBankLogLn2("本地待上传文件路径: " + filePath);
            upload.setRemoteDir(bankFront.folderForRemoteHost);
            WriteBankLogLn2("WTP远程上传目录: " + bankFront.folderForRemoteHost);
            int WtpSleepTime = Integer.parseInt(getBankConfig()
                    .getValueAsString("WtpSleepTime"));
            int WtpReUpload = Integer.parseInt(getBankConfig()
                    .getValueAsString("WtpReUpload"));
            WriteBankLogLn2("尝试上传次数：" + WtpReUpload);
            WriteBankLogLn2("上传间隔时间：" + WtpSleepTime + "毫秒");
            int WtpReUploadCount = Integer.parseInt("1");
            boolean RetransFlag = true;
            while (RetransFlag) {
                WriteBankLogLn2("开始第" + WtpReUploadCount + "次进行WTP上传");
                int uploadResult = upload.upLoadFile();
                if (uploadResult != 0) {
                    if (WtpReUpload <= WtpReUploadCount) {
                        tmpStrRet[0] = "-1";
                        tmpStrRet[1] = upload.getErrorMsg();
                        RetransFlag = false;
                        WriteBankLogLn2("最后一次上传失败原因：" + upload.getErrorMsg());
                    } else {
                        WriteBankLogLn2("第" + WtpReUploadCount + "次上传失败原因：" + upload.getErrorMsg());
                        WtpReUploadCount++;

                    }
                    WriteBankLogLn2("上传延迟" + WtpSleepTime + "毫秒");
                    Thread.sleep(WtpSleepTime);
                } else {
                    WriteBankLogLn2("第" + WtpReUploadCount + "次上传成功!");
                    tmpStrRet[0] = "";
                    tmpStrRet[1] = "upload completed";
                    RetransFlag = false;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

        return tmpStrRet;
    }

    /**
     * WTP文件下载
     *
     * @param p_fileName
     * @return
     * @throws Exception
     */
    protected String[] downFileFromBank(String p_fileName, Date p_date) {
        String[] tmpStrRet = new String[]{"", ""};

        try {
            WtpDownloadFile download = new WtpDownloadFile();
            download.setRemoteFileName(p_fileName);
            WriteBankLogLn2("WTP远程下载文件路径: " + bankFront.folderForRemoteHost
                    + p_fileName);

            download.setOverWrite(true);
            download.setLocalFileDir(getLocalSavePath(p_date));
            int downResult = download.downLoadFile(bankFront.keyID, p_fileName);
            if (downResult != 0) {
                tmpStrRet[0] = "-1";
                tmpStrRet[1] = download.getErrorMsg();
            } else {
                tmpStrRet[0] = "";
                tmpStrRet[1] = "download completed";
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }

        return tmpStrRet;
    }

    /**
     * 路径保证末尾带 \
     *
     * @param p_path
     * @return
     */
    protected String getTrimPath(String p_path) {
        return StringHelper.trimEnd(p_path, File.separator);
    }

    /**
     * 获取本地文件保存目录
     *
     * @param p_date
     * @return
     */
    protected String getLocalSavePath(Date p_date) {
        String tmpByDate = Format.Date8Format.format(p_date);
        tmpByDate = tmpByDate.substring(0, 6) + File.separator
                + tmpByDate.substring(6, 8);
        return getTrimPath(bankFront.bkTransFolder) + File.separator
                + tmpByDate;
    }

    void createFileDir(String p_dir) {
        File mdDir = new File(p_dir);
        if (!mdDir.exists()) {
            mdDir.mkdirs();
        }
    }

    /**
     * 上送银保通服务器
     *
     * @param tmpReqData
     * @param tmpPayDateTime
     * @param tmpUpFileName
     * @param transType
     * @return
     */
    protected String[] sendToBank(String tmpReqData, Date tmpPayDateTime,
                                  String tmpUpFileName, String transType) throws Exception {

        String transMode = getBankConfig().getValueAsString("transMode");
        // WTP方式请求
        if ("WTP".equalsIgnoreCase(transMode)) {
            // 是否合并FINISH文件
            String isCombineFINISH = getBankConfig().getValueAsString(
                    "isCombineFINISH");
            String basePath = getLocalSavePath(tmpPayDateTime);
            // 本地FINISH文件路径
            String locFinishPath = basePath + File.separator + "FINISH";
            if ("1".equals(isCombineFINISH)) {
                locFinishPath += "_LOCAL";
            }
            File locFinishFile = new File(locFinishPath);
            // 上传的文件
            String localUpFilePath = basePath + File.separator + tmpUpFileName;
            FileHelper.writeFile(localUpFilePath, tmpReqData, getCharset());
            String[] tmpStrRet = upFileToBank(localUpFilePath);
            if (tmpStrRet[0].length() == 0) {
                if (locFinishFile.exists()) {
                    String finishContent = FileHelper.readToString(
                            locFinishFile, getCharset());
                    finishContent = finishContent.replace("finish", "");
                    FileHelper.writeFile(locFinishFile, finishContent
                            + tmpUpFileName + "\nfinish", getCharset());
                } else {
                    FileHelper.writeFile(locFinishFile, tmpUpFileName
                            + "\nfinish", getCharset());
                }
            } else {
                return tmpStrRet;
            }
            if ("1".equals(isCombineFINISH)) {
                return tmpStrRet;
            }
            return upFileToBank(locFinishPath);

            // SHARE文件夹方式请求
        } else if ("SHARE".equalsIgnoreCase(transMode)) {
            String tmpUploadFolder = "";
            String tmpDownFolder = "";
            if ("1988".equals(transType)) {
                tmpUploadFolder = bankFront.bkPayFolder;
                tmpDownFolder = bankFront.bkQryPayFolder;
            } else {
                tmpUploadFolder = bankFront.bkRecFolder;
                tmpDownFolder = bankFront.bkQryRecFolder;
            }
            if (StringHelper.isNullOrEmpty(tmpUploadFolder)
                    || StringHelper.isNullOrEmpty(tmpDownFolder)) {
                if ("1988".equals(transType)) {
                    return new String[]{"-1",
                            "缺失'bankFront.bkPayFolder'或'bankFront.bkQryPayFolder'配置或配置有误!"};
                } else {
                    return new String[]{"-1",
                            "缺失'bankFront.bkRecFolder'或'bankFront.bkQryRecFolder'配置或配置有误!"};
                }
            }

            String localUpFilePath = StringHelper.trimEnd(tmpUploadFolder,
                    File.separator)
                    + File.separator
                    + Format.Date8Format.format(tmpPayDateTime)
                    + File.separator + tmpUpFileName;
            FileHelper.writeFile(localUpFilePath, tmpReqData, getCharset());
            createFileDir(StringHelper.trimEnd(tmpDownFolder, File.separator)
                    + File.separator
                    + Format.Date8Format.format(tmpPayDateTime));
            return new String[]{"", "文件已生成，并已上送银保通服务器"};
        } else if ("ftp".equalsIgnoreCase(transMode)) {
            FtpSet ftpSet = bankFront.getFtpSet("ftp");
            FtpReceiver ftpReceiver = null;
            FtpReceiver ftpReceiver1 = null;

            FtpPortClient ftpPortClient = null;
            // 是否合并FINISH文件
            String basePath = getLocalSavePath(tmpPayDateTime);
            String tmpUpFileName1 = tmpUpFileName + ".f";
            String localUpFilePath = basePath + File.separator + tmpUpFileName;
            String localUpFilePath1 = basePath + File.separator + tmpUpFileName1;
            FileHelper.writeFile(localUpFilePath, tmpReqData, getCharset());
            FileHelper.writeFile(localUpFilePath1, "", getCharset());
            try {
                BizFtpClient bizFtp = new BizFtpClient(ftpSet);
                try {
                    bizFtp.connectAndLogin();
                } catch (Exception ex) {
                    WriteBankLogLn(ex);
                    bizFtp.close();
                    return new String[]{"", ex.toString()};
                }
                WriteBankLogLn("本地.TXT文件路径:" + localUpFilePath);
                WriteBankLogLn("本地.TXT.f文件路径:" + localUpFilePath1);
                if (StringHelper.hasAnyChar(ftpSet.upDir)) {
                    WriteBankLogLn("FTP服务器文件上传路径:" + ftpSet.upDir);
                } else {
                    WriteBankLogLn("FTP服务器文件上传路径upDir配置为空");
                }
                WriteBankLogLn2("FTP服务器文件上传地址:" + ftpSet.serverIP + ":" + ftpSet.port);
                if (bizFtp.isLogin()) {
                    byte[] upBytes = FileHelper.readFileBytes(localUpFilePath);
                    BizFtpResp resp = new BizFtpResp();
                    try {
                        int upResult = bizFtp.uploadFile(upBytes, ftpSet.upDir, tmpUpFileName, resp);
                        if (upResult == 1 && getBankConfig().getValueAsBool("isFileNameIndividuation")) {
                            WriteBankLogLn("上传成功" + tmpUpFileName + "文件成功");
                            byte[] upBytes1 = FileHelper.readFileBytes(localUpFilePath1);
                            int upResult1 = bizFtp.uploadFile(upBytes1, ftpSet.upDir, tmpUpFileName1, resp);
                            if (upResult1 == 1) {
                                WriteBankLogLn("上传成功" + tmpUpFileName1 + "文件成功");
                                WriteBankLogLn(bizFtp.sbLog);
                                return new String[]{"", "上传成功"};
                            } else if (upResult1 == -1) {
                                WriteBankLogLn("上传失败" + tmpUpFileName1 + "文件失败");
                                WriteBankLogLn(bizFtp.sbLog);
                                return new String[]{"", "上传失败" + tmpUpFileName1 + "文件失败"};
                            } else {
                                WriteBankLogLn("上传失败，失败原因2" + resp.msg);
                                WriteBankLogLn(bizFtp.sbLog);
                                return new String[]{"-1", resp.msg};
                            }
                        } else if (upResult == -1) {
                            WriteBankLogLn("上传失败" + tmpUpFileName + "文件失败");
                            WriteBankLogLn(bizFtp.sbLog);
                            return new String[]{"", "上传失败" + tmpUpFileName + "文件失败"};
                        } else {
                            WriteBankLogLn("上传失败，失败原因1" + resp.msg);
                            WriteBankLogLn(bizFtp.sbLog);
                            return new String[]{"-1", resp.msg};
                        }

                    } catch (Exception ex) {
                        WriteBankLogLn(ex);
                        return new String[]{"-1", ex.getMessage()};
                    } finally {
                        bizFtp.close();
                    }
                }
                WriteBankLogLn("ftp日志：\r\n" + bizFtp.sbLog);
            } catch (Exception e) {
                if (ftpPortClient != null) {
                    try {
                        ftpPortClient.disconnect();
                    } catch (IOException ie) {
                        e.printStackTrace();
                        WriteBankLogLn(ie);
                    }
                }
            }
            return new String[]{"", "上传成功"};
        } else {
            return new String[]{"-1", "请在对应配置文件中配置正确的传输方式。"};
        }
    }

    //新华个性化FTP的方式
    protected String[] sendToBank(Date tmpPayDateTime, String tmpReqData,
                                  String[] tmpUpFilePrefixs, String tmpReqDataAuth) throws Exception {

        String[] result = new String[]{"", ""};
        String basePath = getLocalSavePath(tmpPayDateTime);
        String tmpUpFileName = tmpUpFilePrefixs[0] + ".txt\n" + tmpUpFilePrefixs[1] + ".txt\n";
        // 本地FINISH文件路径
        String locFinishPath = basePath + File.separator + "FINISH";
        File locFinishFile = new File(locFinishPath);
        //finish文件
        if (locFinishFile.exists()) {
            String finishContent = FileHelper.readToString(
                    locFinishFile, getCharset());
            finishContent = finishContent.replace("finish", "");
            FileHelper.writeFile(locFinishFile, finishContent
                    + tmpUpFileName + "finish", getCharset());
        } else {
            FileHelper.writeFile(locFinishFile, tmpUpFileName
                    + "finish", getCharset());
        }
        // 上传的文件
        String localUpFilePathAuth = basePath + File.separator + tmpUpFilePrefixs[0] + ".txt";
        String localUpFilePath = basePath + File.separator + tmpUpFilePrefixs[1] + ".txt";
        //签约的文件
        FileHelper.writeFile(localUpFilePathAuth, tmpReqDataAuth, getCharset());
        //代扣的文件
        FileHelper.writeFile(localUpFilePath, tmpReqData, getCharset());
        FtpSet ftpSet = bankFront.getFtpSet("ftp");
        WriteBankLogLn("上传地址:" + ftpSet.serverIP + ":" + ftpSet.port);
        FtpReceiver ftpReceiverAuth = null;
        FtpReceiver ftpReceiver = null;
        FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
        String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + Format.Date8Format.format(tmpPayDateTime);
        WriteBankLogLn2("上传ftp服务器目录:" + sftpFilePath + ",上传文件1：" + tmpUpFilePrefixs[0] + ".txt");
        ftpReceiverAuth = ftpPortClient.uploadFileToDir(localUpFilePathAuth, sftpFilePath, tmpUpFilePrefixs[0] + ".txt");
        if (ftpReceiverAuth.isCompleted) {
            WriteBankLogLn2("上传文件1成功，上传文件2：" + tmpUpFilePrefixs[1] + ".txt");
            ftpReceiver = ftpPortClient.uploadFileToDir(localUpFilePath, sftpFilePath, tmpUpFilePrefixs[1] + ".txt");
        } else {
            result[0] = "-1";
            result[1] = "签约文件上传失败，失败原因：" + ftpReceiverAuth.connMsg;
            return result;
        }
        if (!ftpReceiver.isCompleted) {
            result[0] = "-1";
            result[1] = ftpReceiver.connMsg;
        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
            result[0] = "-1";
            result[1] = "上传失败";
        } else {
            FtpPortClient ftpClient = new FtpPortClient(ftpSet);
            ftpClient.deleteFile("FINISH");
            ftpReceiver = ftpClient.uploadFileToDir(locFinishPath, sftpFilePath, "FINISH");
            ftpPortClient.disconnect();
            if (ftpReceiver.isCompleted) {
                result[1] = "文件已生成，并已上送银保通服务器";
            } else {
                result[0] = "-1";
                result[1] = "FINSH文件上送失败，失败原因" + ftpReceiver.connMsg;
            }
        }
        return result;
    }

    protected String[] fetchResFromBank(String tmpDownFileName,
                                        Date tmpPaySendTime, String tmpDownFilePrefix, String transType) {
        String[] result = new String[]{"", ""};
        String transMode = getBankConfig().getValueAsString("transMode");
        // WTP方式请求
        if ("WTP".equals(transMode)) {
            // 状态码, tmpStrQueryResp
            String[] tmpEndRet = downFileFromBank("END", tmpPaySendTime);
            if (tmpEndRet[0].length() == 0) {
                String tmpEndRespPath = getLocalSavePath(tmpPaySendTime)
                        + File.separator + "END";
                WriteBankLogLn2("本地代收付END文件路径：" + tmpEndRespPath);
                String tmpEndFileContent = FileHelper.readFileText(
                        tmpEndRespPath, getCharset());
                WriteBankLogLn2("返回END文件内容:" + tmpEndFileContent);

                String[] tmpFileResp = tmpEndFileContent.split("\n");

                boolean isMatched = false;
                for (String fileName : tmpFileResp) {
                    if (fileName.contains("end")) {
                        continue;
                    }
                    if (!tmpDownFileName.equals(fileName)) {
                        continue;
                    }
                    isMatched = true;
                    String[] tmpDownStrRet = downFileFromBank(
                            tmpDownFileName, tmpPaySendTime);
                    if (tmpDownStrRet[0].length() == 0) {

                        String tmpDownFilePath = getLocalSavePath(tmpPaySendTime)
                                + File.separator + tmpDownFileName;
                        WriteBankLogLn2(
                                "本地代收付结果文件路径：" + tmpDownFilePath);
                        String tmpStrQueryResp = FileHelper.readFileText(
                                tmpDownFilePath, getCharset());

                        WriteBankLogStep3(tmpStrQueryResp);
                        if (StringHelper.isNullOrEmpty(tmpStrQueryResp)) {
                            result[0] = "-1";
                            result[1] = "银行查询结果文件内容为空!";
                            return result;
                        }

                        result[0] = "0";
                        result[1] = tmpStrQueryResp;

                    } else {
                        result[0] = "-1";
                        result[1] = tmpDownStrRet[1];
                    }
                }
                if (!isMatched) {
                    // 下载FAIL文件
                    String[] tmpFailStrRet = downFileFromBank("FAIL",
                            tmpPaySendTime);
                    if (tmpFailStrRet[0].length() == 0) {

                        String tmpFailFilePath = getLocalSavePath(tmpPaySendTime)
                                + File.separator + "FAIL";
                        WriteBankLogLn2("本地代收付FAIL文件路径：" + tmpFailFilePath);
                        String tmpFailQueryResp = FileHelper.readFileText(
                                tmpFailFilePath, getCharset());
                        WriteBankLogStep3(tmpFailQueryResp);
                        String[] failFileArr = tmpFailQueryResp.split("\n");
                        for (String failStr : failFileArr) {
                            if ((tmpDownFilePrefix + ".txt").equals(failStr
                                    .split(" ")[0])) {
                                result[0] = "-1";
                                result[1] = failStr.split(" ")[1];
                            }
                        }
                    } else {
                        result[0] = "-1";
                        result[1] = "下载FAIL文件失败,原因:" + tmpFailStrRet[1];
                    }
                }
            } else {
                result[0] = "-1";
                result[1] = tmpEndRet[1];
            }
            return result;
        } else if ("SHARE".equals(transMode)) {
            String downloadFolder = "";
            if ("1998".equals(transType)) {
                downloadFolder = bankFront.bkQryPayFolder;
            } else {
                downloadFolder = bankFront.bkQryRecFolder;
            }
            if (StringHelper.isNullOrEmpty(downloadFolder)) {
                result[0] = "-1";
                if ("1998".equals(transType)) {
                    result[1] = "缺失'bankFront.bkQryPayFolder'配置或配置有误!";
                } else {
                    result[1] = "缺失'bankFront.bkQryRecFolder'配置或配置有误!";
                }
                return result;
            }
            File tmpFilePath = new File(StringHelper.trimEnd(downloadFolder,
                    File.separator)
                    + File.separator
                    + Format.Date8Format.format(tmpPaySendTime)
                    + File.separator + tmpDownFileName);
            if (!tmpFilePath.exists()) {
                result[0] = "-1";
                result[1] = "回盘文件" + tmpFilePath + "尚未生成!";
                return result;
            }

            WriteBankLogLn2("本地代收付结果文件路径：" + tmpFilePath.getPath());
            String tmpStrQueryResp = FileHelper.readFileText(
                    tmpFilePath.getPath(), getCharset());

            WriteBankLogStep3(tmpStrQueryResp);
            if (StringHelper.isNullOrEmpty(tmpStrQueryResp)) {
                result[0] = "-1";
                result[1] = "银行查询结果文件内容为空!";
                return result;
            }
            result[0] = "0";
            result[1] = tmpStrQueryResp;
            return result;
        } else if ("ftp".equalsIgnoreCase(transMode)) {
            FtpSet ftpSet = bankFront.getFtpSet("ftp");
            FtpReceiver ftpReceiver = null;
            FtpPortClient ftpPortClient = null;
            try {
                ftpPortClient = new FtpPortClient(ftpSet);
                String tmpDownFilePath = getLocalSavePath(tmpPaySendTime) + File.separator + tmpDownFileName;
                WriteBankLogLn2("本地代收付结果文件路径：" + tmpDownFilePath);
                ftpPortClient.setLocalPassiveMode();
                String ftpFilePath = "";
                WriteBankLogLn("下载地址:" + ftpSet.serverIP + ":" + ftpSet.port);
                if (getBankConfig().getValueAsBool("iscallAuth")) {
                    ftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + Format.Date8Format.format(tmpPaySendTime) + "/" + tmpDownFileName;
                    WriteBankLogLn("下载FTP服务器目录为:" + ftpFilePath);
                    ftpReceiver = ftpPortClient.downloadFile(ftpFilePath, tmpDownFilePath);
                } else {
                    ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpDownFilePath);
                }
                if (ftpReceiver.isCompleted) {
                    String tmpStrQueryResp = FileHelper.readFileText(tmpDownFilePath, getCharset());
                    WriteBankLogStep3(tmpStrQueryResp);
                    if (StringHelper.isNullOrEmpty(tmpStrQueryResp)) {
                        result[0] = "-1";
                        result[1] = "银行查询结果文件内容为空!";
                        return result;
                    }
                    result[0] = "0";
                    result[1] = tmpStrQueryResp;
                } else {
                    result[0] = "-1";
                    result[1] = "文件下载失败" + ftpReceiver.connMsg;
                }
            } catch (Exception e) {
                if (ftpPortClient != null) {
                    try {
                        ftpPortClient.disconnect();
                    } catch (IOException ie) {
                        e.printStackTrace();
                        WriteBankLogLn(ie);
                    }
                }
            }
            return result;
        } else {
            return new String[]{"-1", "请在对应配置文件中配置正确的传输方式。"};
        }
    }

}
